﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using DatNuocViet.Models;

namespace DatNuocViet.Areas.Admin.Controllers
{
    [CustomAuthentication]
    public class AdminTourController : Controller
    {
        //
        // GET: /Admin/AdminTour/

        #region TourType
        public ActionResult TourType()
        {
            List<GetTourTypeResult> model = new List<GetTourTypeResult>();
            using (DatNuocVietDbDataContext db = new DatNuocVietDbDataContext())
            {
                model = db.GetTourType().ToList();
            }
            return View(model);
        }

        public ActionResult CreateTourType()
        {
            return View();
        }

        [HttpPost]
        public ActionResult CreateTourType(FormCollection form)
        {
            String TourTypeVn = form["TourTypeVn"].Trim();
            String TourTypeEn = form["TourTypeEn"].Trim();
            String SortOrder = form["SortOrder"].Trim();
            if (ValidateTourType(TourTypeVn, TourTypeEn, SortOrder))
            {
                using (DatNuocVietDbDataContext db = new DatNuocVietDbDataContext())
                {
                    db.InsertTourType(TourTypeVn, TourTypeEn, Convert.ToInt32(SortOrder));
                }
                return Content("<script type='text/javascript'>alert('Thêm loại tour thành công');window.location.replace('/Admin/AdminTour/TourType');</script>");
            }
            ViewBag.message = "Dữ liệu loại tour không đúng";
            return View();
        }

        public ActionResult EditTourType(int id)
        {
            TourTypeDetailsResult model = new TourTypeDetailsResult();
            using (DatNuocVietDbDataContext db = new DatNuocVietDbDataContext())
            {
                model = db.TourTypeDetails(id).SingleOrDefault();
            }
            if (model == null)
                return Redirect(Url.Content("~/Admin/AdminTour/TourType"));
            else
                return View(model);
        }

        [HttpPost]
        public ActionResult EditTourType(FormCollection form)
        {
            String TourTypeVn = form["TourTypeVn"].Trim();
            String TourTypeEn = form["TourTypeEn"].Trim();
            String SortOrder = form["SortOrder"].Trim();
            if (ValidateTourType(TourTypeVn, TourTypeEn, SortOrder))
            {
                try
                {
                    int Id = Convert.ToInt32(form["Id"]);
                    bool Delete = form["Delete"]=="on"?true:false;
                    TourTypeDetailsResult model = new TourTypeDetailsResult();
                    using (DatNuocVietDbDataContext db = new DatNuocVietDbDataContext())
                    {
                        db.UpdateTourType(Id, TourTypeVn, TourTypeEn, Convert.ToInt32(SortOrder), Delete);
                        model = db.TourTypeDetails(Id).SingleOrDefault();
                    }
                    if (Delete == true)
                        return Content("<script type='text/javascript'>alert('Đã xóa loại tour');window.location.replace('/Admin/AdminTour/TourType');</script>");
                    else
                    {
                        ViewBag.message = "Chỉnh sửa loại tour thành công";                       
                        return View(model);
                    }
                }
                catch (Exception)
                {
                    return Redirect(Url.Content("~/Admin/AdminTour/TourType"));
                }
            }
            int Id1 = Convert.ToInt32(form["Id"]);
            TourTypeDetailsResult model1 = new TourTypeDetailsResult();
            using (DatNuocVietDbDataContext db = new DatNuocVietDbDataContext())
            {
                model1 = db.TourTypeDetails(Id1).SingleOrDefault();
            }
            ViewBag.message = "Dữ liệu loại tour không đúng";
            return View(model1);
        }

        #endregion

        #region Tours
        
        public ActionResult Tour()
        {
            int PageIndex = 1;
            string KeyWord = string.Empty;
            int TourType = -1;
            int Featured = -1;
            int onHomepage = -1;
            try
            {
                PageIndex = Convert.ToInt32(Request.QueryString["Page"]);
                if (PageIndex == 0)
                    PageIndex = 1;
            }
            catch (Exception)
            {
                PageIndex = 1;
            }
            if (Request.QueryString["KeyWord"] != null)
            {
                KeyWord = Request.QueryString["KeyWord"].ToString();
            }
            try
            {
                TourType = Convert.ToInt32(Request.QueryString["TourType"]);
                if (TourType == 0)
                    TourType = -1;
            }
            catch (Exception)
            {
                TourType = -1;
            }
            try
            {
                if (!string.IsNullOrEmpty(Request.QueryString["Featured"]))
                {
                    Featured = Convert.ToInt32(Request.QueryString["Featured"]);
                }
                else
                {
                    Featured = -1;
                }
                if (Featured != 0 && Featured != 1 && Featured != -1)
                    Featured = -1;
            }
            catch (Exception)
            {
                Featured = -1;
            }
            try
            {
                if (!string.IsNullOrEmpty(Request.QueryString["onHomepage"]))
                {
                    onHomepage = Convert.ToInt32(Request.QueryString["onHomepage"]);
                }
                else
                {
                    onHomepage = -1;
                }
                if (onHomepage != 0 && onHomepage != 1 && onHomepage != -1)
                    onHomepage = -1;
            }
            catch (Exception)
            {
                onHomepage = -1;
            }
            List<SearchTourResult> model = new List<SearchTourResult>();
            List<GetTourTypeResult> tourType = new List<GetTourTypeResult>();
            int totalPage = 0;
            using (DatNuocVietDbDataContext db = new DatNuocVietDbDataContext())
            {
                model = db.SearchTour(PageIndex, 20, KeyWord, -1, -1, TourType, "[Tours].[NameVn]", "asc", "vn", string.Empty, Featured, onHomepage).ToList();
                totalPage = db.SearchTour(-1, -1, KeyWord, -1, -1, TourType, "[Tours].[NameVn]", "asc", "vn", string.Empty, Featured, onHomepage).Count();
                if (totalPage % 20 == 0)
                    totalPage = totalPage / 20;
                else
                    totalPage = totalPage / 20 + 1;
                if (totalPage == 0)
                    totalPage = 1;
                tourType = db.GetTourType().OrderBy(t=>t.TourTypeVn).ToList();
            }
            ViewBag.TourType = tourType;
            ViewBag.TotalPage = totalPage;
            ViewBag.KeyWord = KeyWord;
            ViewBag.CurrentType = TourType;
            ViewBag.PageIndex = PageIndex;
            ViewBag.CurrentonHomepage = onHomepage;
            ViewBag.CurrentFeatured = Featured;
            return View(model);
        }

        public ActionResult CreateTour()
        {
            List<GetTourTypeResult> tourType = new List<GetTourTypeResult>();
            using (DatNuocVietDbDataContext db = new DatNuocVietDbDataContext())
            {
                tourType = db.GetTourType().ToList();
            }
            ViewBag.TourType = tourType;
            return View();
        }

        [HttpPost]
        public ActionResult CreateTour(FormCollection form)
        {
            string NameVn = form["NameVn"].Trim();
            string DescriptionVn = form["DescriptionVn"].Trim();
            string DetailsVn = form["DetailsVn"];
            string NameEn = form["NameEn"].Trim();
            string DescriptionEn = form["DescriptionEn"].Trim();
            string DetailsEn = form["DetailsEn"];
            string TourType = form["TourType"];
            string Price = form["Price"];
            string Location = form["Location"].Trim();
            bool Featured = form["Featured"] == "on" ? true : false;
            bool onHomepage = form["onHomepage"] == "on" ? true : false;
            if (ValidateTour(NameVn, Price, TourType))
            {
                int id = 0;
                using (DatNuocVietDbDataContext db = new DatNuocVietDbDataContext())
                {
                    id = db.InsertTour(NameVn, NameEn, DescriptionVn, DescriptionEn, HttpUtility.HtmlDecode(DetailsVn), HttpUtility.HtmlDecode(DetailsEn), Convert.ToDecimal(Price), Convert.ToInt32(TourType), Location, Featured, onHomepage); 
                }
                return Content("<script type='text/javascript'>alert('Thêm loại tour thành công');window.location.replace('/Admin/AdminTour/EditTour/" + id + "');</script>");
            }
            ViewBag.message = "Dữ liệu tour không đúng";
            List<GetTourTypeResult> tourType = new List<GetTourTypeResult>();
            using (DatNuocVietDbDataContext db = new DatNuocVietDbDataContext())
            {
                tourType = db.GetTourType().ToList();
            }
            ViewBag.TourType = tourType;
            return View();
        }

        public ActionResult EditTour(int id)
        {
            TourDetailsResult model = new TourDetailsResult();
            List<GetTourTypeResult> tourType = new List<GetTourTypeResult>();
            using (DatNuocVietDbDataContext db = new DatNuocVietDbDataContext())
            {
                model = db.TourDetails(id).SingleOrDefault();
                tourType = db.GetTourType().ToList();
            }
            if (model == null)
                return Redirect(Url.Content("~/Admin/AdminTour/Tour"));
            else
            {
                ViewBag.TourType = tourType;
                return View(model);
            }
        }

        [HttpPost]
        public ActionResult EditTour(FormCollection form)
        {
            string NameVn = form["NameVn"].Trim();
            string DescriptionVn = form["DescriptionVn"].Trim();
            string DetailsVn = form["DetailsVn"];
            string NameEn = form["NameEn"].Trim();
            string DescriptionEn = form["DescriptionEn"].Trim();
            string DetailsEn = form["DetailsEn"];
            string TourType = form["TourType"];
            string Price = form["Price"];
            string Location = form["Location"].Trim();
            bool Featured = form["Featured"] == "on" ? true : false;
            bool onHomepage = form["onHomepage"] == "on" ? true : false;
            if (ValidateTour(NameVn, Price, TourType))
            {
                try
                {
                    int Id = Convert.ToInt32(form["Id"]);
                    bool Delete = form["Delete"] == "on" ? true : false;
                    TourDetailsResult model = new TourDetailsResult();
                    List<GetTourTypeResult> tourType = new List<GetTourTypeResult>();
                    using (DatNuocVietDbDataContext db = new DatNuocVietDbDataContext())
                    {
                        db.UpdateTour(Id, NameVn, NameEn, DescriptionVn, DescriptionEn, HttpUtility.HtmlDecode(DetailsVn), HttpUtility.HtmlDecode(DetailsEn), Convert.ToDecimal(Price), Convert.ToInt32(TourType), Location, Delete, Featured, onHomepage);
                        model = db.TourDetails(Id).SingleOrDefault();
                        tourType = db.GetTourType().ToList();
                    }
                    if (Delete == true)
                        return Content("<script type='text/javascript'>alert('Đã xóa tour');window.location.replace('/Admin/AdminTour/Tour');</script>");
                    else
                    {
                        ViewBag.TourType = tourType;
                        ViewBag.message = "Chỉnh sửa tour thành công";
                        return View(model);
                    }
                }
                catch (Exception)
                {
                    return Redirect(Url.Content("~/Admin/AdminTour/Tour"));
                }
            }
            int Id1 = Convert.ToInt32(form["Id"]);
            TourDetailsResult model1 = new TourDetailsResult();
            List<GetTourTypeResult> tourType1 = new List<GetTourTypeResult>();
            using (DatNuocVietDbDataContext db = new DatNuocVietDbDataContext())
            {
                tourType1 = db.GetTourType().ToList();
                model1 = db.TourDetails(Id1).SingleOrDefault();
            }
            ViewBag.TourType = tourType1;
            ViewBag.message = "Dữ liệu tour không đúng";
            return View(model1);
        }

        [HttpPost]
        public JsonResult GetImages(int id)
        {
            List<GetToursImageResult> model = new List<GetToursImageResult>();
            using (DatNuocVietDbDataContext db = new DatNuocVietDbDataContext())
            {
                model = db.GetToursImage(id).ToList();
            }
            foreach (var item in model)
            {
                item.Images = Url.Content(item.Images.Replace("images/", "images/thumb/"));
            }
            return Json(model);
        }

        [HttpPost]
        public JsonResult ToursImageDetail(int id)
        {
            ToursImageDetailResult model = new ToursImageDetailResult();
            using (DatNuocVietDbDataContext db = new DatNuocVietDbDataContext())
            {
                model = db.ToursImageDetail(id).SingleOrDefault();
                model.Images = Url.Content(model.Images);
            }
            return Json(model);
        }

        [HttpPost]
        public string ToursImagesUpdate(int id, bool deleted, int sortOrder)
        {
            try
            {
                using(DatNuocVietDbDataContext db = new DatNuocVietDbDataContext())
                {
                    db.UpdateToursImage(id, sortOrder, deleted);
                    if(deleted==true)
                        return "Đã xóa hình ảnh";
                    else
                        return "Cập nhật hình ảnh thành công";
                }
            }
            catch(Exception)
            {
                return "Lỗi!";
            }
        }

        #endregion

        #region validate
        [NonAction]
        private bool ValidateTourType(string TourTypeVn, string TourTypeEn, string SortOrder)
        {
            if (string.IsNullOrEmpty(TourTypeVn))
                return false;
            if (string.IsNullOrEmpty(TourTypeEn))
                return false;
            try
            {
                int number = Convert.ToInt32(SortOrder);
            }
            catch (Exception)
            {
                return false;
            }
            return true;
        }

        [NonAction]
        private bool ValidateTour(string NameVn, string Price, string TourType)
        {
            if (string.IsNullOrEmpty(NameVn))
                return false;
            try
            {
                int iTourType = Convert.ToInt32(TourType);
                decimal dPrice = Convert.ToDecimal(Price);
            }
            catch (Exception)
            {
                return false;
            }
            return true;
        }
        #endregion
    }
}
